//
//  XZMemberContentVC.m
//  Teecloud
//
//  Created by PC on 2018/11/5.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZMemberContentVC.h"
#import "XZMemberContentPopVC.h"
#import "XZMemberCheckMsg.h"
#import "XZMemberCheckMsgCell.h"
#import "GMVoiceListModel.h"

@interface XZMemberContentVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UITableView *tableView;
@end
#define Identifier @"XZMemberCheckMsgCell"
@implementation XZMemberContentVC
- (void)dealloc{
    XZLog(@"%s",__FUNCTION__);
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    //监听消息提交回来刷新列表
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getMemberCheckMsgLis) name:@"MemberContent" object:nil];
    [self getMemberCheckMsgLis];
}
#pragma mark - MJRefresh
- (void)getMemberCheckMsgLis{
    self.pageIndex = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:self.userId  forKey:@"memberUserId"];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    kWeakObject(self)
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetMemberCheckMsgList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *newsArray = [XZMemberCheckMsg mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataSource removeAllObjects];
                [weakself.dataSource addObjectsFromArray:newsArray];
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                if (weakself.dataSource.count == 0) {
                    [weakself.tableView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tableView reloadData];
            }else{
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tableView.mj_footer endRefreshing];
            [weakself.tableView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
- (void)getMoreMemberCheckMsgLis{
    self.pageIndex ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:self.userId  forKey:@"memberUserId"];
    
    kWeakObject(self)
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetMemberCheckMsgList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *array = [XZMemberCheckMsg mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataSource addObjectsFromArray:array];
                if (array.count>0) {
                    [weakself.tableView.mj_footer endRefreshing];
                    [weakself.tableView.mj_header endRefreshing];
                    [weakself.tableView reloadData];
                }else{//没有数据的时候就显示暂无数据
                    weakself.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                }
            }else{
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tableView.mj_footer endRefreshing];
            [weakself.tableView.mj_header endRefreshing];
             [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.tableView.mj_footer.hidden = self.dataSource.count > 0? NO:YES;
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    XZMemberCheckMsg *model = self.dataSource[indexPath.row];
    XZMemberCheckMsgCell *memberCheckMsgCell = [tableView dequeueReusableCellWithIdentifier:Identifier];
    memberCheckMsgCell.model = model;
    memberCheckMsgCell.indexPath = indexPath;
    memberCheckMsgCell.parentController = self;
    //点赞
    memberCheckMsgCell.likeBlock = ^(XZMemberCheckMsg * _Nonnull model, NSIndexPath * _Nonnull indexPath) {
        [weakself likeContent:model refreshIndexPath:indexPath];
    };
    //语音读与未读
    memberCheckMsgCell.hasReadBlock = ^(NSInteger index, NSString * _Nonnull voiceID, NSString * _Nonnull voiceStr) {
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"voiceId":voiceID,
                              };
        [MBProgressHUD showHUDAddedTo:weakself.view animated:YES];
        [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"v30.teecloud.cn/ajax-api.ashx?$c=TeeyunApp&$m=PostVoiceReadStatus&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
            [MBProgressHUD hideHUDForView:weakself.view animated:YES];
            if (!error) {
                if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                    if ([voiceStr isEqualToString:@"MSG"]) {
                        //MsgBody.VoiceList
                        for (NSInteger i=0; i<model.MsgBody.VoiceList.count; i++) {
                            GMVoiceListModel *temModel = model.MsgBody.VoiceList[i];
                            if (i == index) {
                                temModel.IsReaded =YES;
                            }
                        }
                    }else{
                        //Quote.VoiceList
                        for (NSInteger i=0; i<model.Quote.VoiceList.count; i++) {
                            GMVoiceListModel *temModel = model.Quote.VoiceList[i];
                            if (i == index) {
                                temModel.IsReaded =YES;
                            }
                        }
                    }
                    [weakself.tableView reloadData];
                }else{
                    [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
                }
            }else{
                [MBProgressHUD showErrorOrSuc:@"请求出错" toView:weakself.view];
            }
        }];
    };
    return memberCheckMsgCell;
}
#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     XZMemberCheckMsg *model = self.dataSource[indexPath.row];
    return model.cellHeight;
}
- (void)likeContent:(XZMemberCheckMsg *)model refreshIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(2) forKey:@"type"];
    [dict setValue:model.MsgBody.Id forKey:@"recId"];
    if (!model.MsgBody.IsLike) {
        [dict setValue:@(1) forKey:@"op"];//点赞
    }else{
        [dict setValue:@(2) forKey:@"op"];//取消点赞
    }
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=LikeOrUnlike&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSString *msg =[responseObject objectForKey:RESULT_NAME_Message];
                if (msg != nil) {
                    [MBProgressHUD showErrorOrSuc:msg toView:weakself.view];
                }
                XZMemberCheckMsg *model = self.dataSource[indexPath.row];
                model.MsgBody.IsLike = !model.MsgBody.IsLike;
                NSInteger likeCount ;
                if (model.MsgBody.IsLike) {
                    likeCount = [model.MsgBody.LikeCount integerValue] + 1;
                }else{
                   likeCount = [model.MsgBody.LikeCount integerValue] - 1;
                }
                model.MsgBody.LikeCount = @(likeCount);
                //将之前的模型给替换
                [self.dataSource replaceObjectAtIndex:indexPath.row withObject:model];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
             [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}

/**
  底部view的点击事件

 @param sender 点击手势
 */
- (IBAction)bottomTapAction:(UITapGestureRecognizer *)sender {
    XZMemberContentPopVC *memberContentPopVC = [[XZMemberContentPopVC alloc] init];
    memberContentPopVC.model = self.groupConfig;
    memberContentPopVC.groupId =self.groupId;
    memberContentPopVC.userId = self.userId;
    [self.navigationController presentSemiViewController:memberContentPopVC withOptions:@{
                                                                                 KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                                 KNSemiModalOptionKeys.animationDuration : @(0.5),
                                                                                 KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                                 }];
}


#pragma mark - Setter
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}

- (UITableView *)tableView{
    if (!_tableView) {
         _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-kNavBarAndStatusBarHeight-kBottomSafeHeight-50) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator =false;
        _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
        //注册
        [_tableView registerNib:[UINib nibWithNibName:@"XZMemberCheckMsgCell" bundle:nil] forCellReuseIdentifier:Identifier];
        //上下拉刷新
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getMemberCheckMsgLis)];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreMemberCheckMsgLis)];
        _tableView.mj_footer.hidden =YES;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
@end
